package com.sm.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpSession;

public class SendMSMUtil{

  public static final String COMMON_TEMPLATE = "SMS_192230333";//登录——验证码模板
  public static final String COMMON_TEMPLATE_INVITE = "SMS_191833692";//下级注册成功通知

  static final String product = "Dysmsapi";
  static final String domain = "dysmsapi.aliyuncs.com";

  static final String accessKeyId = "LTAI4G76vkZYrkqkT9gRjNAQ";//
  static final String accessKeySecret = "WZ5jlvRRiijbn8UJb54kZrxQgJ2gRH";//


	public static SMSBean sendMSM(String recMobile, String tpl_id, JSONObject params) throws ClientException {
		if (tpl_id == null) {
			tpl_id = COMMON_TEMPLATE;
		}

		String	code = RandomUtil.randomNumbers(4);
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");


		IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
		DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Dysmsapi", "dysmsapi.aliyuncs.com");
		IAcsClient acsClient = new DefaultAcsClient(profile);


		SendSmsRequest request = new SendSmsRequest();

		request.setPhoneNumbers(recMobile);

		request.setSignName("童状元");//签名

		request.setTemplateCode(tpl_id);
		if (tpl_id.equals(COMMON_TEMPLATE_INVITE)) {
			if (params != null) {
				request.setTemplateParam(params.toJSONString());
			}
		} else {
			request.setTemplateParam("{\"code\":\"" + code + "\"}");
		}

		request.setOutId("yourOutId");

		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		System.out.println(sendSmsResponse.getMessage());
		boolean success = "OK".equals(sendSmsResponse.getCode());
		if (success) {
			SMSBean smsBean = new SMSBean(null, recMobile, code, "user", new Date());
			CommonUtil.MSG_MAP.put(recMobile, smsBean);
			return smsBean;
		}
		return null;
	}

  public static void clearSendMsg(HttpSession session, String mobile){
      session.removeAttribute(mobile);
      session.removeAttribute(mobile + "Time");
  }

	public static void main(String[] args) throws ClientException {
		JSONObject params = new JSONObject();
		params.put("nickName", "晚什么");
		params.put("phone", "16638395415");
		params.put("time", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
		SendMSMUtil.sendMSM("16638395415", null, params);
	}
}
